package com.ybkj.daijia.server.controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.common.Pager;
import com.ybkj.daijia.config.RentApi;
import com.ybkj.daijia.server.exception.NoPermissionException;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.page.Pageable;
import com.ybkj.daijia.page.impl.PageImpl;
import com.ybkj.daijia.page.impl.PageRequest;
import com.ybkj.daijia.server.model.Vehicle;
import com.ybkj.daijia.server.service.RentShopService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Blazk.
 */
@RestController
@RequestMapping(value = "rentvehicle")
public class RentVehicleController {

    @Autowired
    private RentApi rentApi;
    @Value("${file.upload.url}")
    private String fileUploadUrl;
    @Autowired
    private RentShopService rentShopService;

    @Autowired
    private SettingUtils settingUtils;

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ModelAndView list() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("rentvehicle")) {
            ModelAndView mv = new ModelAndView();

            mv.setViewName("vehicle/list");
            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "add", method = RequestMethod.GET)
    public ModelAndView add() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("rentvehicle")) {
            ModelAndView mv = new ModelAndView();
            mv.addObject("fileUploadUrl", fileUploadUrl);
            mv.setViewName("vehicle/add");
            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "update", method = RequestMethod.GET)
    public ModelAndView update(@RequestParam("id") Long id) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("rentvehicle")) {
            ModelAndView mv = new ModelAndView();
            mv.addObject("id", id);
            mv.addObject("fileUploadUrl", fileUploadUrl);
            mv.setViewName("vehicle/update");
            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    /**
     * 添加车系.
     *
     * @param name           车系名称.
     * @param brandId        品牌id.
     * @param brandName      品牌名称.
     * @param displacementId 排量id.
     * @param displacement   排量名称.
     * @param transmissionId 变速箱id.
     * @param Transmission   变速箱名称.
     * @param type           车辆类型.
     * @param seat           座位数.
     */
    @RequestMapping(value = "insertVehicle", method = RequestMethod.POST)
    public Map<String, Object> insertRentshop(
        @RequestParam("name") String name,
        @RequestParam("brandId") Long brandId,
        @RequestParam("brandName") String brandName,
        @RequestParam("displacementId") Long displacementId,
        @RequestParam("displacement") String displacement,
        @RequestParam("transmissionId") Long transmissionId,
        @RequestParam("transmission") String transmission,
        @RequestParam("typeId") Long typeId,
        @RequestParam("type") String type,
        @RequestParam("seat") Integer seat,
        @RequestParam("pregrant") Double pregrant,
        @RequestParam("illegalDeposit") Double illegalDeposit,
        @RequestParam("discount") Double discount,
        @RequestParam("GPSFree") Double GPSFree,
        @RequestParam("deductible") Double deductible,
        @RequestParam("cap") Double cap,
        @RequestParam("rent") Double rent,
        @RequestParam("proportion") Double proportion,
        @RequestParam("refuelingFee") Double refuelingFee,
        @RequestParam(required = false, value = "photos") String photos,
        @RequestParam(required = false, value = "hoildayFree") String hoildayFree,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> map = new HashMap<String, Object>();
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

        kv.add("name", name);
        kv.add("brandId", String.valueOf(brandId));
        kv.add("brandName", brandName);
        kv.add("displacementId", String.valueOf(displacementId));
        kv.add("displacement", displacement);
        kv.add("transmissionId", String.valueOf(transmissionId));
        kv.add("transmission", transmission);
        kv.add("type", type);
        kv.add("seat", String.valueOf(seat));
        kv.add("pregrant", String.valueOf(pregrant));
        kv.add("illegalDeposit", String.valueOf(illegalDeposit));
        kv.add("discount", String.valueOf(discount));
        kv.add("GPSFree", String.valueOf(GPSFree));
        kv.add("deductible", String.valueOf(deductible));
        kv.add("cap", String.valueOf(cap));
        kv.add("rent", String.valueOf(rent));
        kv.add("hoildayFree", hoildayFree);
        kv.add("typeId", String.valueOf(typeId));
        kv.add("proportion", String.valueOf(proportion));
        kv.add("refuelingFee", String.valueOf(refuelingFee));
        kv.add("photos", photos);
        String result = rentApi.postMultiValueMap(rentApi.getApiBaseURL()
            + RentApi.INSERT_VEHICLE, kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            map.put("message", "车系创建成功");
            map.put("success", true);
        } else {
            map.put("message", jo.getString("message"));
            map.put("success", false);
        }
        return map;
    }

    /**
     * 修改车系.
     *
     * @param name           车系名称.
     * @param brandId        品牌id.
     * @param brandName      品牌名称.
     * @param displacementId 排量id.
     * @param displacement   排量名称.
     * @param transmissionId 变速箱id.
     * @param Transmission   变速箱名称.
     * @param type           车辆类型.
     * @param seat           座位数.
     * @return
     */
    @RequestMapping(value = "updateVehicle", method = RequestMethod.POST)
    public Map<String, Object> updateVehicle(@RequestParam("id") Long id,
        @RequestParam("name") String name,
        @RequestParam("brandId") Long brandId,
        @RequestParam("brandName") String brandName,
        @RequestParam("displacementId") Long displacementId,
        @RequestParam("displacement") String displacement,
        @RequestParam("transmissionId") Long transmissionId,
        @RequestParam("transmission") String transmission,
        @RequestParam("typeId") Long typeId,
        @RequestParam("type") String type,
        @RequestParam("seat") Integer seat,
        @RequestParam("pregrant") Double pregrant,
        @RequestParam("illegalDeposit") Double illegalDeposit,
        @RequestParam("discount") Double discount,
        @RequestParam("GPSFree") Double GPSFree,
        @RequestParam("deductible") Double deductible,
        @RequestParam("proportion") Double proportion,
        @RequestParam("cap") Double cap,
        @RequestParam("rent") Double rent,
        @RequestParam("refuelingFee") Double refuelingFee,
        @RequestParam(required = false, value = "photos") String photos,
        @RequestParam(required = false, value = "hoildayFree") String hoildayFree,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> map = new HashMap<String, Object>();
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

        kv.add("id", String.valueOf(id));
        kv.add("name", name);
        kv.add("brandId", String.valueOf(brandId));
        kv.add("brandName", brandName);
        kv.add("displacementId", String.valueOf(displacementId));
        kv.add("displacement", displacement);
        kv.add("transmissionId", String.valueOf(transmissionId));
        kv.add("transmission", transmission);
        kv.add("type", type);
        kv.add("seat", String.valueOf(seat));
        kv.add("pregrant", String.valueOf(pregrant));
        kv.add("illegalDeposit", String.valueOf(illegalDeposit));
        kv.add("discount", String.valueOf(discount));
        kv.add("GPSFree", String.valueOf(GPSFree));
        kv.add("deductible", String.valueOf(deductible));
        kv.add("cap", String.valueOf(cap));
        kv.add("rent", String.valueOf(rent));
        kv.add("hoildayFree", hoildayFree);
        kv.add("typeId", String.valueOf(typeId));
        kv.add("proportion", String.valueOf(proportion));
        kv.add("refuelingFee", String.valueOf(refuelingFee));
        kv.add("photos", photos);
        String result = rentApi.postMultiValueMap(rentApi.getApiBaseURL()
            + RentApi.UPDATE_VEHICLE, kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            map.put("message", "车系修改成功");
            map.put("success", true);
        } else {
            map.put("message", jo.getString("message"));
            map.put("success", false);
        }
        return map;
    }

    /**
     * 车系上下架
     *
     * @param isGrounding 0下架 1上架.
     * @param id
     */
    @RequestMapping(value = "grouding", method = RequestMethod.POST)
    public Map<String, Object> grouding(@RequestParam("id") Long id,
        @RequestParam("isGrounding") Integer isGrounding,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> map = new HashMap<String, Object>();
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

        kv.add("id", String.valueOf(id));
        kv.add("isGrounding", String.valueOf(isGrounding));

        String result = rentApi.postMultiValueMap(rentApi.getApiBaseURL()
            + RentApi.GROUNDING_VEHICLE, kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            if (isGrounding == 0) {
                map.put("message", "车系下架成功");
                map.put("success", true);
            } else {
                map.put("message", "车系上架成功");
                map.put("success", true);
            }
        } else {
            if (isGrounding == 0) {
                map.put("message", "车系下架失败");
                map.put("success", false);
            } else {
                map.put("message", "车系上架失败");
                map.put("success", false);
            }
        }
        return map;
    }

    /**
     * 查询车系.
     *
     * @param id 门店车系id.
     */
    @RequestMapping(value = "findById", method = RequestMethod.GET)
    public Map<String, Object> findById(@RequestParam("id") Long id,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, String> kv = new HashMap<String, String>();
        StringBuilder builder = new StringBuilder();
        builder.append(rentApi.getApiBaseURL()).append(RentApi.SELECT_VEHICLE_BYID)
            .append("?appkey={appkey}");
        if (null != id) {
            kv.put("id", String.valueOf(id));
            builder.append("&id={id}");
        }
        String result = rentApi.get(builder.toString(), kv, settingUtils.get());
        Map<String, Object> map = new HashMap<String, Object>();
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().create();
                Vehicle vehicle = gson.fromJson(data.toString(), Vehicle.class);
                vehicle.setGPSFree(Double.valueOf(data.get("gpsfree").toString()));
                map.put("success", true);
                map.put("data", vehicle);
            } else {
                map.put("success", false);
                map.put("message", jo.getString("message"));
            }
        }
        return map;
    }

    /**
     * 查询车系.
     *
     * @param isGrounding 上下架车系 0下架 1上架.
     * @param page
     * @param rows
     * @return
     */
    @RequestMapping(value = "findVehicle", method = RequestMethod.GET)
    public Page<Vehicle> selectRentOrders(
        @RequestParam(required = false, value = "isGrounding") Integer isGrounding,
        @RequestParam(required = false, value = "rows") Integer rows,
        @RequestParam(required = false, value = "page") Integer page,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        Map<String, String> kv = new HashMap<String, String>();
        StringBuilder builder = new StringBuilder();
        builder.append(rentApi.getApiBaseURL()).append(RentApi.SELECT_VEHICLE)
            .append("?appkey={appkey}");
        if (null != isGrounding) {
            kv.put("isGrounding", String.valueOf(isGrounding));
            builder.append("&isGrounding={isGrounding}");
        }
        page = Pager.getPage();
        rows = Pager.getLimit();
        if (rows != null) {
            kv.put("rows", String.valueOf(rows));
            builder.append("&rows={rows}");
        }
        if (page != null) {
            kv.put("page", String.valueOf(page + 1));
            builder.append("&page={page}");
        }
        String result = rentApi.get(builder.toString(), kv, settingUtils.get());
        List<Vehicle> vehicles = new ArrayList<Vehicle>();
        long total = 0;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");

            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray jsonArray = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().create();
                vehicles = gson.fromJson(jsonArray.toString(), new TypeToken<List<Vehicle>>() {
                }.getType());

            }
        }
        return new PageImpl<Vehicle>(vehicles, pageable, total);
    }

    @RequestMapping(value = "deleteHolidayById", method = RequestMethod.POST)
    public Map<String, Object> deleteHolidayById(
        @RequestParam("id") Long id,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> map = new HashMap<String, Object>();
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("id", String.valueOf(id));
        String result = rentApi
            .postMultiValueMap(rentApi.getApiBaseURL() + RentApi.DELETE_VEHICLEID_HOLIDAY, kv,
                settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            map.put("message", "删除成功");
            map.put("success", true);
        } else {
            map.put("message", jo.getString("message"));
            map.put("success", false);
        }
        return map;
    }


    @ResponseBody
    @RequestMapping(value = "findVehicleByparams", method = RequestMethod.GET)
    public Page<Vehicle> findVehicle(
        @RequestParam(required = false, value = "typeId") Long typeId,
        @RequestParam(required = false, value = "brandId") Long brandId,
        @RequestParam(required = false, value = "displacementId") Long displacementId,
        @RequestParam(required = false, value = "transmissionId") Long transmissionId,
        @RequestParam(required = false, value = "price") Integer price,
        @RequestParam(required = false, value = "seat") Integer seat,
        @RequestParam(required = false, value = "page") Integer page,
        @RequestParam(required = false, value = "rows") Integer rows,
        @RequestParam("shopId") Long shopId,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        Map<String, String> kv = new HashMap<String, String>();
        StringBuilder builder = new StringBuilder();
        builder.append(rentApi.getApiBaseURL()).append(RentApi.SELECT_VEHICLE_BYPARAM)
            .append("?appKey={appkey}");
        if (null != shopId) {
            kv.put("shopId", String.valueOf(shopId));
            builder.append("&shopId={shopId}");
        }
        if (null != brandId) {
            kv.put("brandId", String.valueOf(brandId));
            builder.append("&brandId={brandId}");
        }
        if (null != displacementId) {
            kv.put("displacementId", String.valueOf(displacementId));
            builder.append("&displacementId={displacementId}");
        }
        if (null != transmissionId) {
            kv.put("transmissionId", String.valueOf(transmissionId));
            builder.append("&transmissionId={transmissionId}");
        }
        if (null != price) {
            kv.put("price", String.valueOf(price));
            builder.append("&price={price}");
        }
        if (null != seat) {
            kv.put("seat", String.valueOf(seat));
            builder.append("&price={seat}");
        }

        page = Pager.getPage();
        rows = Pager.getLimit();
        if (rows != null) {
            kv.put("rows", String.valueOf(rows));
            builder.append("&rows={rows}");
        }
        if (page != null) {
            kv.put("page", String.valueOf(page + 1));
            builder.append("&page={page}");
        }
        String result = rentApi.get(builder.toString(), kv, settingUtils.get());
        List<Vehicle> vehicles = new ArrayList<Vehicle>();
        long total = 0;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");

            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray jsonArray = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().create();
                vehicles = gson.fromJson(jsonArray.toString(), new TypeToken<List<Vehicle>>() {
                }.getType());

            }
        }
        return new PageImpl<Vehicle>(vehicles, pageable, total);
    }
}
